<template>
  <div class="container-big wing-blank invoice-page">
    <!-- <div class="uncan-2019-text" />
    <div class="alibaba-design" />
    <div class="uncan-right" /> -->
    <invoiceHead :billlcode="billlcode" :totalPrice="totalPrice" />

    <form name="form" class="invoice-page-form form" @submit="handleSubmit">
      <fieldset class="form-fieldset">
        <legend class="form-fieldset-legend">
          发票类型
        </legend>
        <div style=" padding-bottom: 16px;" class="form-fieldset-content">
          <div class="form-control">
            <div class="form-control-radio-group">
              <label>
                <input :style="[{borderColor:'#fff'},{backgroundColor:formData.type=='elec'?$store.state.themeColor:''}]" v-model="formData.type" type="radio" name="type" value="elec">电子发票
              </label>
              <label>
                <input :style="[{borderColor:'#fff'},{backgroundColor:formData.type=='paper'?$store.state.themeColor:''}]" v-model="formData.type" type="radio" name="type" value="paper">纸质发票
              </label>
            </div>
          </div>
          <div class="form-tip">
            电子发票与纸质发票具有同等法律效力, 均可支持报销入账.
          </div>
        </div>
      </fieldset>

      <fieldset class="form-fieldset">
        <legend class="form-fieldset-legend">
          发票信息
        </legend>
        <div class="form-fieldset-content">
          <div class="form-control">
            <label class="form-control-label">
              发票类型
            </label>
            <input v-if="formData.type=='elec'" disabled value="增值税普通发票" type="text" class="form-control-input">
            <input v-if="formData.type=='paper'" disabled value="增值税专用发票" type="text" class="form-control-input">
          </div>
          <div class="form-control">
            <label class="form-control-label">
              开具类型
            </label>
            <div class="form-control-radio-group">
              <label>
                <input :style="[{borderColor:'#fff'},{backgroundColor:formData.isIndividuals=='1'?$store.state.themeColor:''}]" v-model="formData.isIndividuals" type="radio" name="isIndividuals" value="1">企业单位
              </label>
              <label v-if="formData.type=='elec'">
                <input :style="[{borderColor:'#fff'},{backgroundColor:formData.isIndividuals=='0'?$store.state.themeColor:''}]" v-model="formData.isIndividuals" type="radio" name="isIndividuals" value="0">个人/非企业单位
              </label>
            </div>
          </div>
          <div class="form-control">
            <label class="form-control-label" for="companyName">
              发票抬头
            </label>
            <input v-if="formData.isIndividuals == 1" id="companyName" v-model.trim="formData.companyName" type="text" placeholder="请输入企业名称" class="form-control-input">
            <input v-else disabled id="companyName" v-model.trim="individual" type="text" class="form-control-input">
          </div>
          <div class="form-control" v-if="formData.isIndividuals == 1">
            <label class="form-control-label" for="code">
              企业税号
            </label>
            <input id="code" v-model.trim="formData.dutyParagraph" type="text" placeholder="请输入企业纳税人识别号" class="form-control-input">
          </div>
          <div class="form-control" v-if="formData.type=='paper'">
            <label class="form-control-label" for="payerBank">
              开户银行
            </label>
            <input id="payerBank" v-model.trim="formData.payerBank" type="text" placeholder="请输入基本开户银行名称" class="form-control-input">
          </div>
          <div class="form-control" v-if="formData.type=='paper'">
            <label class="form-control-label" for="payerAccount">
              开户账号
            </label>
            <input id="payerAccount" v-model.trim="formData.payerAccount" type="text" placeholder="请输入基本开户账号" class="form-control-input">
          </div>
          <div class="form-control" v-if="formData.type=='paper'">
            <label class="form-control-label" for="payerAddress">
              注场地址
            </label>
            <input id="payerAddress" v-model.trim="formData.payerAddress" type="text" placeholder="请输入注册场所地址" class="form-control-input">
          </div>
          <div class="form-control" v-if="formData.type=='paper'">
            <label class="form-control-label" for="payerPhoneNumber">
              固定电话
            </label>
            <input id="payerPhoneNumber" v-model.trim="formData.payerPhoneNumber" type="text" placeholder="请输入注册固定电话" class="form-control-input">
          </div>
          <div class="form-control">
            <label class="form-control-label" for="remark">
              备注内容
            </label>
            <input id="remark" v-model.trim="formData.remark" type="text" placeholder="请输入备注内容" class="form-control-input">
          </div>
        </div>
      </fieldset>
      <div class="form-fieldset-tip">
        提示：税务局要求, 发票抬头为企业时, 须填写企业纳税人识别号 (公司税号)
      </div>

      <fieldset class="form-fieldset">
        <legend class="form-fieldset-legend">
          接收方式
        </legend>
        <div class="form-fieldset-content">
          <template v-if="formData.type === 'elec'">
            <div class="form-control">
              <label class="form-control-label" for="email">
                接收邮箱
              </label>
              <input id="email" v-model.trim="formData.email" type="text" placeholder="请输入接收邮箱" class="form-control-input">
            </div>
          </template>
          <template v-else>
            <div class="form-control">
              <label class="form-control-label" for="consignee">
                收货人
              </label>
              <input id="consignee" v-model.trim="formData.consignee" type="text" placeholder="请输入收货人姓名" class="form-control-input">
            </div>
            <div class="form-control">
              <label class="form-control-label" for="phoneNumber">
                联系电话
              </label>
              <input id="phoneNumber" v-model.trim="formData.phoneNumber" type="text" placeholder="请输入联系电话" class="form-control-input">
            </div>
            <div class="form-control arrow" @click.stop="isAddrPickerOpenned = true">
              <label class="form-control-label" for="area">
                所在区域
              </label>
              <input id="area" v-model="formData.area" disabled type="text" placeholder="请选择所在区域" class="form-control-input">
            </div>
            <div class="form-control">
              <label class="form-control-label" for="address">
                详细地址
              </label>
              <input id="address" v-model.trim="formData.address" type="text" placeholder="请输入详细地址" class="form-control-input">
            </div>
          </template>
        </div>
      </fieldset>
      <addr-picker :open="isAddrPickerOpenned" title="请选择区域" @cancel="isAddrPickerOpenned = false" class="maxWidth" @confirm="handleSelectArea" />
      <co-button :loading="loading" class="submit-button submit-button-invoice " type="submit" block color="primary">
        申请提交
      </co-button>
    </form>
    <!-- 确认发票信息 -->
    <van-popup position="bottom" class="van-popup-invoice" v-model="invoiceFormConfirmAlert">
      <div class="maxWidth">
        <div class="from-tit-invoice ">
          <img class="from-tit-invoice-img" src="https://gw.alicdn.com/tfs/TB1vpgTHcbpK1RjSZFyXXX_qFXa-200-200.png">
          温馨提示:发票信息确认之后，无法更改，请仔细核查！
        </div>
        <invoiceFormConfirm style="margin-top: 0px" :formData="formData" :totalPrice="totalPrice" />
        <div class="ucan-ticket-footer">
          <co-button @click="invoiceFormConfirmAlert=false" class="ucan-ticket-action" color="outline">
            取消
          </co-button>
          <co-button :loading="loading" @click="sureSubmit()" class="ucan-ticket-action" color="primary">
            确认
          </co-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import AddrPicker from "@/components/addr-picker";
import validator from "validator";
import invoiceService from "@/api/invoice.js";
import invoiceHead from "./invoiceHead";
import invoiceFormConfirm from "./invoice-form-confirm";

const formValidateRules = {
  companyName: [{ required: true, message: "请输入发票抬头" }],
  dutyParagraph: [{ required: true, message: "请输入税号" }],
  payerBank: [{ required: true, message: "请输入基本开户银行名称" }],
  payerAccount: [{ required: true, message: "请输入基本开户账号" }],
  payerAddress: [{ required: true, message: "请输入注册场所地址" }],
  payerPhoneNumber: [{ required: true, message: "请输入注册固定电话" }],
  remark: [{ required: true, message: "请输入备注" }],
  email: [
    { required: true, message: "请输入接收邮箱" },
    { validator: validator.isEmail, message: "请输入合法的接收邮箱" }
  ],
  consignee: [{ required: true, message: "请输入收货人" }],
  phoneNumber: [
    { required: true, message: "请输入联系电话" },
    { validator: validator.isMobilePhone, message: "请输入合法的电话" }
  ],
  area: [{ required: true, message: "请选择区域" }],
  address: [{ required: true, message: "请输入详细地址" }]
};

export default {
  components: {
    AddrPicker,
    invoiceFormConfirm, //确认发票信息
    invoiceHead //订单头部，如订单号，订单金额等
  },
  data() {
    return {
      invoiceFormConfirmAlert: false,
      orderId: "",
      projectId: "",
      loading: false,
      individual: "个人",
      billlcode: "", //订单号,
      totalPrice: "", //订单总价
      formData: {
        type: "elec", //发票类型
        isIndividuals: 1, //开具类型
        companyName: "", //发票抬头
        dutyParagraph: "", //企业税号
        payerBank: "", //开户银行
        payerAccount: "", //开户账号
        payerAddress: "", //注场地址
        payerPhoneNumber: "", //固定电话
        remark: "", //备注内容
        area: "", //所在区域
        consignee: "", //收货人
        phoneNumber: "", //联系电话
        address: "", //详细地址
        email: "" //接收邮箱,
        // // 测试
        // type: "paper", //发票类型
        // isIndividuals: 1, //开具类型
        // companyName: "发票抬头", //发票抬头
        // dutyParagraph: "企业税号", //企业税号
        // payerBank: "开户银行", //开户银行
        // payerAccount: "开户账号", //开户账号
        // payerAddress: "注场地址", //注场地址
        // payerPhoneNumber: "固定电话", //固定电话
        // remark: "备注内容", //备注内容
        // area: "所在区域", //所在区域
        // consignee: "收货人", //收货人
        // phoneNumber: "联系电话", //联系电话
        // address: "详细地址", //详细地址
        // email: "接收邮箱" //接收邮箱,
      },
      isAddrPickerOpenned: false
    };
  },
  watch: {
    // 选择电子发票，可以是企业或个人，
    // 选择纸质发票，只能为企业，
    "formData.type"() {
      this.formData.isIndividuals = 1;
    },
    "formData.dutyParagraph"() {
      if (/[\u4E00-\u9FA5]/g.test(this.formData.dutyParagraph)) {
        this.$toast("企业税号不能为汉字");
        this.formData.dutyParagraph = "";
      }
    }
  },
  created() {
    console.log(this.$route.query);
    const { orderId, projectId, billlcode, totalPrice } = this.$route.query;
    this.billlcode = billlcode;
    this.totalPrice = totalPrice;
    if (!orderId) {
      this.$toast("缺少orderId");
      return;
    }
    // if (!projectId) {
    //   this.$toast("缺少projectId");
    //   return;
    // }
    this.orderId = orderId || sessionStorage.getItem("orderIdUcan");
    this.projectId = projectId;
  },
  methods: {
    // 提交数据
    async handleSubmit(e) {
      e.preventDefault();
      const {
        type, //发票类型
        isIndividuals //开具类型
      } = this.formData;

      let validateFields = []; //要验证的字段
      if (type === "elec") {
        validateFields = ["companyName", "email"];
      } else {
        validateFields = [
          "companyName",
          "dutyParagraph",
          "payerBank",
          "payerAccount",
          "payerAddress",
          "payerPhoneNumber",
          "consignee",
          "phoneNumber",
          "area",
          "address"
        ];
      }

      if (isIndividuals == 0) {
        // 假如是个人, 发票抬头统一使用个人
        this.formData.companyName = "个人";
      } else {
        // 假如是公司, 还需要检验税号
        validateFields.push("dutyParagraph");
      }

      let errors = [];
      errors = this.validteForm(this.formData, validateFields);

      if (errors.length) {
        this.$toast(errors[0].message);
        return;
      }
      console.log(this.formData);
      this.invoiceFormConfirmAlert = true;
    },
    // 确认提交
    async sureSubmit() {
      try {
        this.loading = true;
        let subData = {
          invoiceType: this.formData.type == "elec" ? 0 : 1, //* 发票类型 0增值税普通发票 1增值税专用发票
          submitType: this.formData.type == "elec" ? 0 : 1,
          orderId: this.orderId,
          headerType: this.formData.isIndividuals,
          headerName: this.formData.companyName,
          taxNum: this.formData.dutyParagraph,
          remark: this.formData.remark,
          consignee: this.formData.consignee,
          phoneNumber: this.formData.phoneNumber,
          address: this.formData.area + "  /  " + this.formData.address,
          email: this.formData.email,
          payerBank: this.formData.payerBank, //开户银行
          payerAccount: this.formData.payerAccount, //开户账号
          payerAddress: this.formData.payerAddress, //注场地址
          payerPhoneNumber: this.formData.payerPhoneNumber //固定电话
        };
        // 如果是个人
        if (this.formData.isIndividuals != 1) {
          subData.headerName = "个人";
          subData.taxNum = "";
        }
        const resData = await invoiceService.addInvoice(subData);
        console.log("resData", resData);
        this.loading = false;
        if (resData.success) {
          await this.$confirm("发票申请提交成功, 请稍后查询", {
            title: "提交成功",
            okLabel: "确认",
            showCancel: false
          });
          this.$router.back();
        }
      } catch (err) {
        this.loading = false;
      }
    },
    // 选择区域
    handleSelectArea(data) {
      const [province, city, area] = data;
      this.formData.area = area
        ? `${province.text} / ${city.text} / ${area.text}`
        : `${province.text} / ${city.text}`;
      // this.formData.area = area ? area.value : city.value;
      this.isAddrPickerOpenned = false;
    },
    // 数据整理
    validteForm(formData, fieldsToValidated = []) {
      const errors = [];
      for (let i = 0; i < fieldsToValidated.length; i++) {
        const fieldName = fieldsToValidated[i];
        const fieldValue = formData[fieldName];
        const rules = formValidateRules[fieldName];
        for (let j = 0; j < rules.length; j++) {
          const rule = rules[j];
          if (rule.required && !fieldValue) {
            errors.push({ field: fieldName, message: rule.message });
          } else if (rule.validator && !rule.validator(fieldValue)) {
            errors.push({ field: fieldName, message: rule.message });
          }
        }
      }
      return errors;
    }
  }
};
</script>
<style lang="less">
.invoice-page {
  padding-top: 36px;
  padding-bottom: 180px;
  font-size: 24px;

  .uncan-right {
    z-index: 1;
  }

  .alibaba-design,
  .uncan-2019-text {
    position: static;
  }

  .van-picker__title,
  .van-picker__cancel,
  .van-picker__confirm {
    font-size: 32px;
    color: #4a4a4a;
  }

  .submit-button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
  }
}

.invoice-page-form {
  margin-top: 68px;
  position: relative;
  z-index: 1;
}

.form-fieldset {
  text-align: left;
  border: none;
  margin-bottom: 18px;
  padding: 0;
}

.form-fieldset-legend {
  display: block;
  color: #fff;
  margin-bottom: 6px;
  font-size: 28px;
}

.form-fieldset-content {
  padding: 6px 26px 36px;
  padding-bottom: 6px;
  background-color: rgba(0, 0, 0, 0.4);
}

.form-control {
  padding: 30px 0;
  font-size: 26px;
  display: flex;
  justify-content: space-between;

  &.arrow {
    background: url(https://img.alicdn.com/tfs/TB1d9jlLzDpK1RjSZFrXXa78VXa-16-28.png)
      no-repeat;
    background-size: 16px 28px;
    background-position: right center;
  }

  & + .form-control {
    border-top: 1px solid rgba(151, 151, 151, 0.2);
  }

  @radio-out-circel-size: 14px;
  @radio-inner-circel-size: 6px;
  @radio-inner-pos: (@radio-out-circel-size - @radio-inner-circel-size) / 2;
  input[type="radio"] {
    width: @radio-out-circel-size; /*no*/
    height: @radio-out-circel-size; /*no*/
    border: 1px solid #fff; /*no*/
    border-radius: 50%;
    margin-right: 10px;
    position: relative;
    transition: 300ms border-color;
    vertical-align: middle;
    top: -2px;

    &:before {
      display: block;
      position: absolute;
      content: " ";
      top: @radio-inner-pos - 1px; /*no*/
      left: @radio-inner-pos - 1px; /*no*/
      height: @radio-inner-circel-size; /*no*/
      width: @radio-inner-circel-size; /*no*/
      border-radius: 50%;
      background-color: transparent;
      transition: 300ms background-color;
    }
  }
}

.form-control-radio-group {
  label + label {
    margin-left: 50px;
  }
}

.form-control-label {
  flex: 0 0 160px;
}

.form-control-input,
.form-control-radio-group {
  flex: 1 1 auto;
}

.form-control-input {
  &:disabled {
    opacity: 0.9;
  }
}

.form-tip {
  color: #737375;
  font-size: 24px;
}

.form-fieldset-tip {
  color: #d8d8d8;
  margin: -10px 0 56px;
  font-size: 20px;
  text-align: left;
}
.co-list-item-par > div {
  margin-top: 0px !important;
}
.order-no-label-span {
  display: inline-block;
  min-width: 116px;
  text-align: left;
  margin-right: 38px;
}
.van-popup-invoice {
  background: #131416
    url(https://img.alicdn.com/tfs/TB1b4pCHxYaK1RjSZFnXXa80pXa-1500-2668.png)
    no-repeat;
  background-size: 100%;
  padding: 0px 26px;
}
.ucan-ticket-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 20px;
  color: fade(#eee, 70%);
  padding-top: 28px;
  padding-bottom: 24px;
  &.only-action {
    justify-content: center;
  }
}

.ucan-ticket-action {
  width: 280px;
  height: 72px;
  font-size: 30px;
}
.from-tit-invoice {
  width: 100%;
  height: auto;
  text-align: left;
  /* font-family: PingFangSC-Regular; */
  font-size: 22px;
  color: #b9b9bb;
  position: relative;
  text-indent: 36px;
  margin-top: 16px;
  margin-bottom: 6px;
}
.from-tit-invoice-img {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 26px;
  height: auto;
  margin-right: 6px;
}
</style>

